package com.Drools.CIPS.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.prowidesoftware.swift.io.parser.SwiftParser;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.model.field.*;

public class MTToSwiftMessage {


    private static String fileToString(String path) {
        StringBuilder sb = new StringBuilder("");
        try(BufferedReader br = new BufferedReader(new FileReader(path));) {
            char[] cbuf = new char[1024];
            int len;
            while ((len = br.read(cbuf)) != -1){
                sb.append(cbuf,0,len);
                //由于汉字等某些字符  一个字符占不等的 字节 所以有汉字的用字符流好
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
    public static SwiftMessage swift(String path){
        String mt103 = fileToString(path);
//        System.out.println(mt103);
        // 方法一
        SwiftParser parser = new SwiftParser(mt103);
        SwiftMessage swiftMessage = null;
        try {
            swiftMessage = parser.message();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println(swiftMessage);
        SwiftBlock4 block4 = swiftMessage.getBlock4();

        System.out.println("---block4------------------------");
//        System.out.println(block4);
//        di3(block4);
        Field fieldByName = swiftMessage.getBlock4().getFieldByName("33B");
//        System.out.println(swiftMessage.getBlock4().getFieldByName("36"));
//        Object
//        Field fieldByName = block4.getFieldByName("33B");
//        System.out.println(fieldByName.getComponents());
        return swiftMessage;
    }

    private static void di3(SwiftBlock4 block4) {
        System.out.println("---23B------------------------");
        Field fieldByName1 = block4.getFieldByName("23B");
        System.out.println(fieldByName1.getComponent(1));
        System.out.println(block4.getFieldByName("23E").getComponent(1));
        System.out.println(toEquals(block4.getFieldByName("23E").getComponent(1),
                new String[]{"SDVA","TELB","PHOB","INTC"}));
        System.out.println(block4.getFieldByName("36")==null);
    }

    public static Object toZzz(SwiftMessage sw,int w1,String s,int w2){
        Object re = null;
        if(w1 == 4){
            if(w2<0){
                re = sw.getBlock4().getFieldByName(s);
            }else{
                re = sw.getBlock4().getFieldByName(s).getComponent(w2);
            }
        }
        return re;
    }

    public static boolean toEquals(Object z,String[] ss){
        String zz = z.toString();
        for (String s:ss){
            if(zz.equals(s)){
                return true;
            }
        }
        return false;
    }
}
